const { regist, find, update, findtoid } = require("../model/userModel")
const { addLog, findLog } = require("../model/logs")
const bcryptjs = require("bcryptjs");
const moment = require("moment")
const jwt = require("jsonwebtoken")
//注册
const register = async function (req, res) {
    //查看用户名、密码是否传入
    // isNameAndPwd(req,res)
    if (!req.body.name || !req.body.pwd) {
        res.send({ state: false, status: 0, msg: "name||pwd必填" })
        return;
    }
    //先查询数据库是否有相同的用户名
    let isNameArr = await find({ name: req.body.name })
    if (isNameArr) {
        if (!isNameArr.length) {
            //用户名未注册
            //加密密码
            let salt = 10;
            let hash = await bcryptjs.hash(req.body.pwd, salt);
            //查看是否是超级管理员root
            let authorization = req.body.authorization || req.headers.authorization || req.query.authorization;
            let secrect = "How_are_you";
            jwt.verify(authorization, secrect, function (err, decode) {
                console.log(decode.name);
                if (decode.name === "root") {  //-------同时注释这四行可以取消权限
                    //拥有注册的权限  仅仅只有root拥有权限
                    req.body.pwd = hash;
                    // let result = await regist(req.body);
                    if (regist(req.body)) {
                        res.send({ state: true, status: 1, msg: "注册成功" })
                    } else {
                        res.send({ state: false, status: 0, msg: "注册失败" })
                    }
                } else {   //-------
                    //权限不足
                    res.send({ state: false, status: 0, msg: "没有该权限(注册用户)" })  //-------
                }   //-------
            })

        } else {
            res.send({ state: false, status: 0, msg: "用户名已注册" })
        }
    } else {
        res.send({ state: false, status: 0, msg: "查询失败" })
    }
}

//登录
const loginer = async function (req, res, next, isupdata = false) {
    //查看用户名、密码是否传入
    if (!req.body.name || !req.body.pwd) {
        res.send({ state: false, status: 0, msg: "name||pwd必填" })
        return;
    }
    let isloginArr = await find({ name: req.body.name });
    if (isloginArr) {
        if (isloginArr.length) {//存在该用户
            //校验密码
            let isVerify = await bcryptjs.compare(req.body.pwd, isloginArr[0].pwd)
            if (isVerify) {
                //密码已经校验成功
                if (isupdata) {
                    return true;
                } else {
                    //1.在用户登入成功的时候 使用jwt生成一串数字签名token 返回给前端
                    //2.调用jsonwebtoken下面的sign方法 进行签名
                    let secrect = "How_are_you";
                    let payload = {
                        name: isloginArr[0].name,
                        phone: isloginArr[0].phone,
                        nickname: isloginArr[0].nickname
                    }//1.payload载荷 2.secrect 加密字符串 3.{expirsIn:秒} 生效时间
                    let token = jwt.sign(payload, secrect, {
                        expiresIn: 60 * 50 //token生效时间
                    })
                    //登入成功后记录登入日志
                    //查找上次登入的日志
                    let lastLoginQuery = {
                        username: req.body.name
                    }
                    //获取上次登入结果
                    let findLogResult = await findLog(lastLoginQuery)
                    //如果是第一次登入 让lastLogin的值设置空
                    let lastLogin;
                    if (findLogResult.length !== 0) {
                        findLogResult = findLogResult[0]
                        lastLogin = {
                            loginTime: findLogResult['nowLogin']['loginTime'],
                            ip: findLogResult['nowLogin']['ip']
                        }
                    } else {
                        lastLogin = {
                            loginTime: "",
                            ip: ""
                        }
                    }
                    //获取登入ip
                    var ip =
                        req.headers['x-forwarded-for'] || req.ip || req._remoteAddress || (req.connection && req.connection.remoteAddress) || undefined;
                    ip = ip.substr(7)
                    console.log("这是登入ip(在controll/users_controll.js--登陆功能中--90行):", ip);
                    //创建登入事件
                    let loginTime = moment().format("YYYY/MM/DD HH:mm:ss")
                    let nowLogin = {
                        ip,
                        loginTime,
                    }
                    let log = {
                        username: req.body.name,
                        lastLogin,
                        nowLogin,
                    }
                    let setLogResult = await addLog(log)
                    console.log(setLogResult, "本次登录以及上次登录")
                    res.send({ state: true, status: 1, msg: "登录成功", _id: isloginArr[0]._id, token })
                }
            } else {
                if (isupdata) {
                    return false
                } else {
                    res.send({ state: false, status: 0, msg: "账号或者密码错误" })
                }
            }
        } else {
            res.send({ state: false, status: 0, msg: "没有该账户" })
        }
    } else {
        res.send({ state: false, status: 0, msg: "查询失败" })
    }
}

//查询所有管理员信息
const findusers = async function (req, res, next) {
    let query = {}
    if (req.query.name) { query.name = req.query.name }
    console.log(query);

    let findResult = await find(query);
    if (findResult) {//查找成功
        //遍历数组 去除pwd
        findResult = findResult.map(item => {
            return {
                _id: item._id,
                name: item.name,
                phone: item.phone,
                email: item.email,
                nickname: item.nickname,
                des: item.des
            }
        })
        res.send({ state: true, status: 1, findResult })
    } else {
        res.send({ state: false, status: 0, msg: "查询失败" })
    }
}

//修改个人信息(传入_id)  不包括密码
const updataer = async function (req, res, next) {
    // 获取_Id 作为更新条件
    let { _id } = req.body;
    let query = {
        _id
    }
    let updated = {}
    let { name, phone, email, nickname, des } = req.body
    if (name) { updated.name = name }
    if (phone) { updated.phone = phone }
    if (email) { updated.email = email }
    if (nickname) { updated.nickname = nickname }
    if (des) { updated.des = des }
    console.log(updated);

    let result = await update(query, updated)
    console.log(result);

    if (result.nModified !== 0) {
        res.send({ state: true, status: 1, msg: "基本信息更新成功" })
    } else {
        res.send({ state: false, status: 1, msg: "信息相同,更新失败" })
    }
}
//修改密码
const uppwder = async function (req, res, next) {
    //查看用户名、密码、新密码是否传入
    if (!req.body._id || !req.body.pwd || !req.body.newpwd) {
        res.send({ state: false, status: 0, msg: "新密码和旧密码必填" })
        return;
    }
    let { _id } = req.body
    //校验密码
    let isloginArr = await findtoid({ _id })
    console.log(isloginArr);
    if (isloginArr) {
        if (isloginArr.length) {//存在该用户
            //校验密码
            let isVerify = await bcryptjs.compare(req.body.pwd, isloginArr[0].pwd)
            if (isVerify) {
                let query = { _id }
                let salt = 10;
                let hash = await bcryptjs.hash(req.body.newpwd, salt);
                let updated = { pwd: hash }
                let result = await update(query, updated)
                if (result.nModified !== 0) {
                    res.send({ state: true, status: 1, msg: "密码修改成功" })
                } else {
                    res.send({ state: false, status: 0, msg: "密码修改失败" })
                }
            } else {
                res.send({ state: false, status: 0, msg: "密码错误" })
            }
        } else {
            res.send({ state: false, status: 0, msg: "没有该账户" })
        }
    } else {
        //查询失败
        res.send({ state: false, status: 0, msg: "数据库查询失败" })
    }
}


module.exports = {
    register, loginer, findusers, updataer, uppwder
}